// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: fengyang

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/gateio/symbology/currency.h"

namespace coin2::exchange::gateio::symbology {

class GateioProduct : public base::symbology::SpotProduct<GateioCurrency, GateioProduct>,
                     public base::symbology::ProductFromStrMixin<GateioProduct> {
 public:
  using BaseProduct = SpotProduct<GateioCurrency, GateioProduct>;

  using ExchangeType = base::market::ExchangeType;
  using MarketType = base::market::MarketType;
  using CurrencyT = GateioCurrency;
  static const ExchangeType kExchange = ExchangeType::Gateio;
  static const MarketType kMarketType = MarketType::Spot;

 public:
  GateioProduct(const GateioCurrency& base, const GateioCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToGateioNativeProduct(base, quote),
            ToGateioNativeProduct(base, quote),
            base::market::ExchangeType::Gateio) {}

 public:
  static std::unique_ptr<GateioProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<GateioCurrency> base_ptr;
    std::unique_ptr<GateioCurrency> quote_ptr;
    bool success =
        ParseGateioNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<GateioProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseGateioNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<GateioCurrency>* base_ptr,
      std::unique_ptr<GateioCurrency>* quote_ptr) {
    std::vector<std::string> splitted;
    splitted = Split(product_str, "_");
    if (splitted.size() != 2) {
      return false;
    }

    *base_ptr = GateioCurrency::FromNativeStrNoThrow(splitted[0], resolve_timestamp);
    *quote_ptr = GateioCurrency::FromNativeStrNoThrow(splitted[1], resolve_timestamp);
    return true;
  }

  static std::string ToGateioNativeProduct(
      const GateioCurrency& base,
      const GateioCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency() << "_" << quote.native_currency();
    return ss.str();
  }
};

}  // namespace coin2::exchange::gateio::symbology
